var signature = "AAT";
$('#loading').show();
var w = $(window).width()
console.log(w)
$(window).load(function() {
    $('#loading').hide();
    var validate = {
        flag: false,
        value: ''
    };
    var errs = {};
    var rigiCount = 59;
    var count = rigiCount;
    var apiUrl = [
        "https://acat.lpaat888.com",
    ];
    function handleApi({
                           url,
                           method,
                           data,
                           options,
                           success,
                           error,
                           apiUrlCounter = 0,
                       }) {
        $.ajax({
            url: apiUrl[apiUrlCounter] + url,
            ...options,
            method,
            data,
            success: function (res) {
                if (success) success(res);
            },
            error: function () {
                if (apiUrlCounter < apiUrl.length - 1) {
                    apiUrlCounter++;
                    handleApi({
                        url,
                        options,
                        method,
                        data,
                        success,
                        error,
                        apiUrlCounter,
                    });
                } else {
                    if (error) error();
                }
            },
        });
    }
    window.initNECaptcha &&
        window.initNECaptcha({
                captchaId: '456cd203ae994b32bebdbf7e8fb8abb2',
                element: 'body',
                mode: 'popup',
                width: '320px',
                lang: 'zh-CN',
                onReady: function() {
                    console.log('ready');
                },
                onVerify: function(err, data) {
                    if (err) {
                        validate = {
                            flag: false,
                            value: ''
                        }
                        return;
                    }
                    validate = {
                        flag: true,
                        value: data.validate
                    }
                    console.log('validate=', validate);
                    //易盾验证成功
                    countDown();
                },
            },
            function(instance) { //初始化完成
                instanceObj = instance;
            },
            function(err) {
                validate = {
                    flag: false,
                    value: ''
                }
            },
        );


    $('#getCode').click(function() {
        vailPhone();
        if (!errs.phone) return;
        instanceObj.refresh();
        instanceObj.popUp();
    })

    $('#account').on('input blur propertychange', function() {
        vailPhone();
    })

    $('#password').on('input blur propertychange', function() {
        vailPass();
    });

    $('#code').on('input blur propertychange', function() {
        vailCode();
    });

    $('#name').on('input blur propertychange', function() {
        vailName();
    });

    $('#idCard').on('input blur propertychange', function() {
        vailIdCard();
    });

    $('#email').on('input blur propertychange', function() {
        vailEmail();
    });

    $('#submit').click(function() {
        if( $('#name').attr('isReal') == '1' ) vailIdCard();
        vailName();
        vailPhone();
        vailPass();
        vailCode();
        if (errs.phone && errs.pass && errs.code) {
            $('.modal').show();
            $('#btnLoad').show();
            var driverType;
            if (!!window.navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
                driverType = 3;
            } else {
                driverType = 2;
            }
            handleApi({
                url: '/customer/createAccount',
                method: 'POST',
                options: {
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    headers: {
                        'Content-Type': 'application/json;charset=utf8',
                        'sourceUrl': window.location.href
                    },
                },
                data: JSON.stringify({
                    userLevel: 'MIN',
                    chineseName: $.trim(errs.name),
                    idDocumentNumber: $.trim(errs.idCard),
                    mobilePhone: $.trim($('#account').val()),
                    captcha: $.trim($('#code').val()),
                    password: $.trim($('#password').val()),
                    driverType: driverType,
                    signature: signature,
                }),
                success: function(res) {
                    $('#submit').show();
                    $('#btnLoad').hide();
                    $('#modal').hide();
                    if (res.code == 'OK') {
                        toastShow('注册成功');
                        $('#account').val('');
                        $('#password').val('');
                        $('#code').val('');
                        errs.uuid = res.data.updateCustomerUuid;
                        // window.location.href = `https://acat.antofx.com/further-information/${uuid}`;
                        $('.mask').show()
                    } else {
                        toastShow(res.msg);
                    }
                },
                error: function() {
                    $('#submit').show();
                    $('#btnLoad').hide();
                }
            })
        }
    })


    function vailPhone() {
        var phone = $.trim($('#account').val());
        if (!(/^(((1[3456789][0-9]{1})|(15[0-9]{1})|111)+\d{8})$/.test(phone))) {
            errs.phone = false;
            $('#phoneErr').html('请输入正确的手机号码').css({
                'visibility': 'initial'
            });
            $('#getCode').attr('disabled',true);
        } else {
            errs.phone = true;
            $('#phoneErr').css('visibility', 'hidden');
            $('#getCode').removeAttr('disabled');
        }
    }

    function vailPass() {
        var pass = $.trim($('#password').val());
        if (!(/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,16}$/.test(pass))) {
            errs.pass = false;
            $('#passErr').html('请输入6-16位密码，包含字母和数字').css({
                'visibility': 'initial'
            });
        } else {
            errs.pass = true;
            $('#passErr').css('visibility', 'hidden');
        }
    }

    function countDown() {
        var search = window.location.search;
        handleApi({
            url: '/customer/sendOpenMessage',
            method: "POST",
            options: {
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                headers: {
                    'Content-Type': 'application/json;charset=utf8',
                    'sourceUrl': window.location.href
                },
            },
            data: JSON.stringify({
                mobilePhone: $.trim($('#account').val()),
                validate: validate.value,
                trackParameters: search.slice(1, search.length),
                signature: signature,
            }),
            success: function(res) {
                if (res.code === 'OK') {
                    $('#getCode').hide();
                    $('#countDown').show();
                    toastShow('验证码发送成功');
                    window.timer = setInterval(function() {
                        if (count > 1) {
                            count--;
                        } else {
                            count = rigiCount;
                            clearInterval(window.timer);
                            $('#getCode').show();
                            $('#countDown').hide();
                        }
                        $('#countDown').html(count + 's后获取')
                    }, 1000)
                } else {
                    toastShow(res.msg);
                }
            }
        })
    }

    function vailCode() {
        var code = $.trim($('#code').val());
        if (!(/^\d{4}$/.test(code))) {
            errs.code = false;
            $('#codeErr').html('验证码错误').css({
                'visibility': 'initial'
            });
        } else {
            errs.code = true;
            $('#codeErr').css('visibility', 'hidden');
        }
    }

    function toastShow(str) {
        $('#toast').html(str).show();
        setTimeout(function() {
            $('#toast').hide();
        }, 1000)
    }

    $('#close').click(function() {
        $('.kf').hide()
    })

    $('#maskbtn').click(function() {
        vailName()
        vailIdCard()
        if (errs.name && errs.idCard) {
            handleApi({
                url: '/customer/updateAccount',
                method: "POST",
                options: {
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    headers: {
                        'Content-Type': 'application/json;charset=utf8'
                    },
                },
                data: JSON.stringify({
                    chineseName: errs.name,
                    email: '',
                    idDocumentNumber: errs.idCard,
                    updateCustomerUuid: errs.uuid
                }),
                success: function(res) {
                    if (res.code != 'OK') {
                        toastShow(res.msg);
                    } else {
                        handleApi({
                            url: '/customer/generateUrl',
                            method: "POST",
                            options: {
                                contentType: "application/json; charset=utf-8",
                                headers: {
                                    'Content-Type': 'application/json;charset=utf8'
                                },
                            },
                            data: JSON.stringify({
                                updateCustomerUuid: errs.uuid
                            }),
                            success: function(res) {
                                if (res.code != 'OK') {
                                    toastShow(res.msg);
                                } else {
                                    down();
                                }
                            }
                        })
                    }
                }
            })

        }
    })

    function vailName() {
        var name = $.trim($('#name').val());
        let reg = /^[\u4e00-\u9fa5]{1,15}$/;
        if (!reg.test(name) || name == '') {
            errs.name = false
            $("#errName").html("请输入您的真实姓名").css('visibility', 'initial');
        } else {
            errs.name = name
            $("#errName").css('visibility', 'hidden')
        }
    }

    function vailIdCard() {
        var idCard = $.trim($('#idCard').val());
        let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
        if (!reg.test(idCard)) {
            errs.idCard = false
            $("#errIdCard").html("请输入正确的身份证号码").css('visibility', 'initial');
        } else {
            errs.idCard = idCard
            $("#errIdCard").css('visibility', 'hidden')
        }
    }

    function vailEmail() {
        var email = $.trim($('#email').val());
        let reg = /^(?!\s+)[A-Za-z0-9_\-\.]+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (!reg.test(email)) {
            errs.email = false
            $("#errEmail").html("请输入正确的邮箱").css('visibility', 'initial');
        } else {
            errs.email = email
            $("#errEmail").css('visibility', 'hidden')
        }
    }

    function down() {
        var agent = navigator.userAgent.toLowerCase();
        var android = agent.indexOf("android");
        var iphone = agent.indexOf("iphone");
        var ipad = agent.indexOf("ipad");
        var equipmentType = ''
        if (android != -1) {
            equipmentType = "android";
        }
        if (iphone != -1 || ipad != -1) {
            equipmentType = "ios";
        }

        const hrefConfig = {
            // 'ios': 'https://apps.apple.com/app/apple-store/id1600200673',
            'android': 'https://downloads.cjgh888.cn/source/material/HXJY_360_sem.apk'
        }

        if(equipmentType == ''){// pc端 显示二维码
            $('.kyc-bg').hide()
            $('.kyc-bg-success').show()
        }

        if(typeof hrefConfig[equipmentType] == "undefined" ){
            console.log('无效下载链接');
            return false;
        }

        window.location.href = hrefConfig[equipmentType];
        $('.mask').hide();
    }

    $('.kyc-close').click(function () {
        $('.mask').hide();
        $('.kyc-bg').show();
        $('.kyc-bg-success').hide();
    })

    $('.downloadNow').click(function() {
        down()
    })

    $('.maskclose').click(function() {
        $('.mask').hide()
    })
})